<template>
  <div>
    <!-- -->
    <van-nav-bar :title="good.name" left-text="返回" left-arrow @click-left="onClickLeft" />
    <!-- 内容 -->
    <div class="content">
      <div class="imgName">
        <div class="img"><img :src="good.coverURL"></div>
        <div class="engName">英文名：{{ good.engName || '暂无' }}</div>
      </div>
      <div class="text">
        <div class="nation">国家：{{ good.nation || '暂无' }}</div>
        <div class="characters">性格：{{ good.characters || '暂无' }}</div>
        <div class="easyOfDisease">易得疾病：{{ good.easyOfDisease || '暂无' }}</div>
        <div class="life">寿命：{{ good.life || '暂无' }}</div>
        <div class="price">价格：{{ good.price || '暂无' }}</div>
      </div>
      <div class="introduce">
        <div class="desc">简介：{{ good.desc || '暂无' }}</div>
        <div class="feedPoints">饲养：{{ good.feedPoints || '暂无' }}</div>
      </div>
    </div>
    <!--  -->
    <van-goods-action>
      <van-goods-action-button color="#8ec5fc" type="danger" text="萌宠更详细信息^-^" @click="Detailed" />
      <van-goods-action-button v-if="!isDisabled" color="#d299c2" type="danger" text="好可爱，收藏吧^-^" @click="Collection" />
      <van-goods-action-button v-else color="#d299c2" type="danger" text="您已收藏啦^-^" @click="Collection" />
    </van-goods-action>
  </div>
</template>

<script>
import localforage from 'localforage';

export default {
  name: 'Vue2Goodinfo',

  data() {
    return {
      good: {},
      isDisabled: false,
    };
  },
  mounted() {
    //在生命周期钩子中调用数据初始化方法
    this.getgood(this.$route.query.goodid)
  },
  created() {
    localforage.getItem('loginStatus').then((status) => {
      if (status === null || status === false) {
        this.$toast({
          message: '您未登录！',
          // icon: '../../assets/maomao.png',
          icon: 'https://imgs.qiubiaoqing.com/qiubiaoqing/imgs/62d45cdc270fbOUI.gif',
          // icon: '@/assets/img/maomao.png',
        });
        this.$router.replace("/Login");
      }
    });
    // this.toggleFavorite();
    // setTimeout(() => { // 添加延时
    //   this.toggleFavorite(); // 在这里调用 toggleFavorite 方法
    // }, 100); // 延时 1 秒
  },
  watch: {
    good: {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.toggleFavorite(); // 当 good 发生变化时自动调用 toggleFavorite 方法
        }
      },
      deep: true,
    },
  },

  methods: {

    //返回上一级
    onClickLeft() {
      this.$router.go(-1);
    },
    //跳转详情
    Detailed() {
      // console.log(this.good.url);
      // this.$router.push(this.good.url);
      this.$toast({
        message: '3秒后跳转到浏览器！',
        // icon: '../../assets/maomao.png',
        icon: 'https://ts1.cn.mm.bing.net/th/id/R-C.b1149d2634220449d577bf591bb4652d?rik=Ek1VfcCMUHZtlA&riu=http%3a%2f%2fwx2.sinaimg.cn%2flarge%2f86883a42gy1fiega8zj9jj20j60ixjw9.jpg&ehk=6Xrv6LJBX1Pyi%2bF7el6Q%2bTrxAG22WCnf5ZF7lzm7v4w%3d&risl=&pid=ImgRaw&r=0',
        // icon: '@/assets/img/maomao.png',
      });
      // window.location.href = this.good.url;
      setTimeout(() => {
        window.location.href = this.good.url;
        // window.location.replace(this.good.url);
      }, 3000);
    },
    //收藏(记得作只能收藏一次的判断)
    Collection() {
      // 获取用户登录ID
      localforage.getItem('currentUser').then((res) => {
        // 检查是否已经收藏
        localforage.getItem('CollectiblePets').then((favorites) => {
          let isFavorited = false;
          favorites = favorites || [];
          // 遍历收藏列表，检查是否已经收藏
          for (let i = 0; i < favorites.length; i++) {
            if (favorites[i].userId === res.id && favorites[i].collection.id === this.good.id) {
              isFavorited = true;
              break;
            }
          }
          if (isFavorited) {
            // 已收藏，给出提示或执行其他操作
            this.$toast({
              message: '该萌宠已收藏！',
              // icon: '../../assets/maomao.png',
              icon: 'https://imgs.qiubiaoqing.com/qiubiaoqing/imgs/62d45cdc270fbOUI.gif',
              // icon: '@/assets/img/maomao.png',
            });
          } else {
            // 未收藏，添加到收藏列表并存储
            favorites.push({ userId: res.id, collection: this.good });
            localforage.setItem('CollectiblePets', favorites).then(() => {
              this.$toast({
                message: '收藏成功！',
                // icon: '../../assets/maomao.png',
                icon: 'https://ts1.cn.mm.bing.net/th/id/R-C.b1149d2634220449d577bf591bb4652d?rik=Ek1VfcCMUHZtlA&riu=http%3a%2f%2fwx2.sinaimg.cn%2flarge%2f86883a42gy1fiega8zj9jj20j60ixjw9.jpg&ehk=6Xrv6LJBX1Pyi%2bF7el6Q%2bTrxAG22WCnf5ZF7lzm7v4w%3d&risl=&pid=ImgRaw&r=0',
                // icon: '@/assets/img/maomao.png',
              });
            });
            this.toggleFavorite();
          }
        });
      }).catch((err) => {
        // 处理获取用户ID失败的情况
        console.log(err);
      });
    },
    toggleFavorite() {
      localforage.getItem('currentUser').then((res) => {
        // 检查是否已经收藏
        localforage.getItem('CollectiblePets').then((favorites) => {
          let isFavorited = false;
          favorites = favorites || [];
          // 遍历收藏列表，检查是否已经收藏
          for (let i = 0; i < favorites.length; i++) {
            if (favorites[i].userId === res.id && favorites[i].collection.id === this.good.id) {
              isFavorited = true;
              break;
            }
          }
          if (isFavorited) {
            this.isDisabled = true;
          } else {
            this.isDisabled = false;

          }
        });
      }).catch((err) => {
        // 处理获取用户ID失败的情况
        console.log(err);
      });
    },
    // this.$toast({
    //   message: '收藏成功！',
    //   // icon: '../../assets/maomao.png',
    //   icon: 'https://ts1.cn.mm.bing.net/th/id/R-C.b1149d2634220449d577bf591bb4652d?rik=Ek1VfcCMUHZtlA&riu=http%3a%2f%2fwx2.sinaimg.cn%2flarge%2f86883a42gy1fiega8zj9jj20j60ixjw9.jpg&ehk=6Xrv6LJBX1Pyi%2bF7el6Q%2bTrxAG22WCnf5ZF7lzm7v4w%3d&risl=&pid=ImgRaw&r=0',
    //   // icon: '@/assets/img/maomao.png',
    // });
    //获取宠物信息
    getgood(goodid) {
      this.$axios({
        url: "./localdata/petlist.json"
      }).then(res => {
        // console.log(res);
        for (const item of res.data) {
          if (item.id == goodid) {
            this.good = item
            // console.log(item);
            break;
          }
        }
        if (Object.keys(this.good).length === 0) {
          this.$router.replace("/404")
        }
      })
    },
  },
};
</script>
<style scoped>
/* * {
  background-color: #0002;
} */
.van-goods-action {
  box-shadow: 0px -2px 10px rgba(0, 0, 0, 0.3);
  /* border-radius: 2vw 2vw 0 0; */
}


div.content {
  width: 100%;
  height: 100%;
}

div.imgName {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

div.img {
  margin-top: 2vw;
}

img {
  width: 330px;
  height: 250px;
}

div.engName {
  margin-top: 2vw;
  font-size: 5vw;
}

div.text {
  margin-top: 2vw;
  padding: 2vw;
  font-size: 5vw;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  height: 38vw;
}

div.introduce {
  margin-top: 2vw;
  padding: 2vw;
  font-size: 5vw;
  display: flex;
  flex-direction: column;
}

div.feedPoints {
  margin: 2vw 0 16vw 0;
}
</style>